package god

import (
	"gopkg.in/macaron.v1"
	"log"
	"reflect"
)

type God struct {
	*macaron.Macaron

	Log *log.Logger

	db interface{}
}

func Fighting() *God {

	//m := &God{Macaron: macaron.New()}
	//m.Use(macaron.Logger())
	//m.Use(macaron.Recovery())
	//m.Use(macaron.Static("public"))
	//return m

	app := &God{Macaron: macaron.Classic()}

	//设置配置文件路径
	//macaron.SetConfig("")

	return app
}

func (this *God) Middleware(m Middleware) *God {
	this.Use(m.Process)
	return this
}

func (this *God) Action(group string, classes ...IClass) *God {

	this.Group(group, func() {
		for _, clazz := range classes {
			clazz.Route(this) // 遍历所有IClass的具体实现， 并注册Route  这才是关键 !!!

			//TODO: 采用反射注入到控制器中
			vClass := reflect.ValueOf(clazz).Elem()
			if vClass.NumField() > 0 {
				if this.db != nil {
					vClass.Field(0).Set(reflect.New(vClass.Field(0).Type().Elem()))
					vClass.Field(0).Elem().Set(reflect.ValueOf(this.db).Elem())
				}
			}
		}
	})

	return this
}

func (this *God) Start(ip string, port int) {
	this.Run(ip, port)
}

//设置数据库链接对象
func (this *God) DB(db interface{}) *God {
	this.db = db
	return this
}
